<template>
    <div class="">
        <div class="">
            <h4 class="margin_bottom20">角色列表</h4>
            <el-row type="flex" class="row-bg" justify="space-between">
              <el-col :span="12">
                <!--<el-button-group>-->

                <el-button type="primary" size="small" @click="addRole"><i class="iconfont icon-plus"></i>新增</el-button>
                <el-button type="primary" size="small" @click="deleteRole" icon="delete">删除</el-button>

              <!--</el-button-group>-->
              </el-col>
              <el-col :span="6">
                <el-input placeholder="搜索..." size="small" v-model="searchKey"><el-button slot="append" icon="search" @click="search"></el-button></el-input>
              </el-col>
            </el-row>
            <template>
                <el-table :data="tableData" border style="width: 100%; text-align: center;margin-top:10px;" @selection-change="handleSelectionChange" v-loading.body="loading">
                    <el-table-column header-align="center" type="selection"></el-table-column>
                    <el-table-column header-align="center" prop="innerName" label="编码"></el-table-column>
                    <el-table-column header-align="center" prop="roleName" label="角色名"></el-table-column>
                    <el-table-column header-align="center" prop="userName" label="创建人"></el-table-column>
                    <el-table-column header-align="center" prop="displayOrder" label="排序"></el-table-column>
                    <el-table-column header-align="center" width="250" label="操作">
                        <template slot-scope="scope">
                            <el-button size="small" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
                            <el-button size="small" @click="handleMemberManager(scope.$index, scope.row)">人员管理</el-button>
                            <el-button size="small" @click="handleMenu(scope.$index, scope.row)">菜单权限</el-button>
                        </template>
                    </el-table-column>
                </el-table>
                <el-pagination
                    @size-change="handleSizeChange"
                    @current-change="handleCurrentChange"
                    :current-page="currentPage"
                    :page-sizes="[2,20,50,100,200]"
                    :page-size="limit"
                    layout="total, sizes, prev, pager, next, jumper"
                    :total="total">
                </el-pagination>
            </template>
        </div>

        <!-- 表单弹窗 -->
        <el-dialog title="添加角色" v-model="dialogAddVisible" :show-close="false">

            <el-form :model="role"  ref="addForm">
                <el-form-item label="编码" :label-width="formLabelWidth" prop="innerName"
                              :rules="[{ required: true, message: '名称不能为空'}]">
                    <el-input v-model="role.innerName" auto-complete="off"></el-input>
                </el-form-item>
                <el-form-item label="角色名" :label-width="formLabelWidth" prop="roleName"
                              :rules="[{ required: true, message: '名称不能为空'}]">
                    <el-input v-model="role.roleName" auto-complete="off"></el-input>
                </el-form-item>
                <el-form-item label="显示顺序" :label-width="formLabelWidth" prop="displayOrder"
                              :rules="[
                                { required: true, message: '不能为空'},
                                { type: 'number', message: '必须为数字值'}
                                ]"
                >
                    <el-input v-model.number="role.displayOrder" auto-complete="off"></el-input>
                </el-form-item>
                </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="reset('add')">取 消</el-button>
                <el-button type="primary" @click="submit('addForm')">确 定</el-button>
            </div>
        </el-dialog>

        <!-- 表单弹窗 -->
        <el-dialog title="修改角色" v-model="dialogEditVisible" :show-close="false">

            <el-form :model="role" ref="editForm">
                <el-form-item label="编码" :label-width="formLabelWidth" prop="innerName"
                              :rules="[{ required: true, message: '名称不能为空'}]">
                    <el-input v-model="role.innerName" auto-complete="off" :disabled="true"></el-input>
                </el-form-item>
                <el-form-item label="角色名" :label-width="formLabelWidth" prop="roleName"
                              :rules="[{ required: true, message: '名称不能为空'}]">
                    <el-input v-model="role.roleName" auto-complete="off"></el-input>
                </el-form-item>
                <el-form-item label="显示顺序" :label-width="formLabelWidth" prop="displayOrder"
                                :rules="[
                                { required: true, message: '不能为空'},
                                { type: 'number', message: '必须为数字值'}
                                ]"
                >
                    <el-input v-model.number="role.displayOrder" auto-complete="off"></el-input>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="reset('edit')">取 消</el-button>
                <el-button type="primary" @click="submit('editForm')">确 定</el-button>
            </div>
        </el-dialog>

        <!-- Table -->
        <el-dialog title="人员管理" v-model="users.dialogVisible">
            <el-row type="flex" class="row-bg" justify="space-between">
                <el-col :span="8">

                    <el-select
                            v-model="users.addUser"
                            filterable
                            remote
                            placeholder="请输入真实姓名"
                            :remote-method="searchUser"
                                >
                        <el-option
                                v-for="item in users.searchUsers"
                                :key="item.value"
                                :label="item.label"
                                :value="item.value">
                        </el-option>
                    </el-select>
                    <el-button type="primary" size="small"  @click="addUser">快速添加</el-button>
                </el-col>
            </el-row>
            <el-table :data="users.tableData" border style="width: 100%; text-align: center;margin-top:10px;" @selection-change="handleUsersSelectionChange" v-loading.body="users.loading">
                <el-table-column prop="accountName" label="账号"></el-table-column>
                <el-table-column prop="realName" label="真实姓名"></el-table-column>
                <el-table-column label="操作">
                    <template slot-scope="scope">
                        <el-button
                                size="small"
                                @click="handleRemoveUser(scope.$index, scope.row)">移除</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <el-pagination
                    @size-change="handleUsersSizeChange"
                    @current-change="handleUsersCurrentChange"
                    :current-page="users.currentPage"
                    :page-sizes="[2,20,50,100,200]"
                    :page-size="users.limit"
                    layout="total, sizes, prev, pager, next, jumper"
                    :total="users.total">
            </el-pagination>
        </el-dialog>

        <el-dialog title="菜单权限分配" v-model="menuManageVisible" :show-close="false">
            <el-tree :data="treeJson" ref="tree"
                    show-checkbox
                    node-key="id"
                    :props="defaultProps"
                    :expand-on-click-node="true"
                    :default-checked-keys="treeChecks"
                    >
            </el-tree>
            
            <div slot="footer" class="dialog-footer">
                <el-button @click="menuManageVisible = false">取 消</el-button>
                <el-button type="primary" @click="submitMenuMange()">确 定</el-button>
            </div>
        </el-dialog>

        <div class="clear"></div>
    </div>
</template>
<script>

    export default {
        name:'app',
        data() {
            return {
                tableData: [],
                dialogAddVisible: false,
                dialogEditVisible: false,
                roleInit: '',
                role: {
                    id: '',
                    innerName: '',
                    roleName:'',
                    displayOrder:0,
                    creatorId: '',
                    deptId: '',
                    createTime: ''
                },
                formLabelWidth: '120px',
                currentPage: 1,
                total: 0,
                limit: 100,
                searchKey: '',
                selectedRoles: [],
                deleteFlag: true,
                loading: false,
                currentId:'',
                users:{
                    tableData: [],
                    currentPage: 1,
                    total: 0,
                    limit: 100,
                    searchKey: '',
                    loading: false,
                    currentId:'',
                    selectedItems:[],
                    currentItemInfo:{},
                    dialogVisible: false,
                    addUser:'',
                    searchUsers:[],
                },
                menuManageVisible: false,
                treeJson: [],
                defaultProps: {
                    children: 'children',
                    label: 'label'
                },
                treeChecks: [],
                canDG: true
            }
        },
    methods: {
        handleSizeChange:function(val){
            this.limit=val;
            this.getStore();
            //console.log(val);
        },
        handleUsersSizeChange:function(val){
            this.users.limit=val;
            this.getUsersStore();
        },
        handleCurrentChange:function(val){
            this.currentPage=val;
            //console.log(val);
            this.getStore();
        },
        handleUsersCurrentChange:function(val){
            this.users.currentPage=val;
            this.getUsersStore();
        },

        initEntity() {
            var vm = this;
            this.role = {
                id: '',
                innerName: '',
                roleName:'',
                displayOrder:0,
                creatorId: '',
                deptId: '',
                createTime: ''
            };
        },

        addRole:function(){
            this.initEntity();
            this.dialogAddVisible = true;
            this.dialogEditVisible = false;
        },
        handleEdit:function(index,row){
            if (row.creatorId === localStorage.userId) {
                 this.dialogAddVisible = false;
                this.dialogEditVisible = true;
                this.currentId=row.id;
                this.role=row;
            } else {
                this.$message({
                        type: 'warning',
                        message: '无权修改'
                });
            }
            //console.log('row',row);
        },
        deleteRole:function(){
            var vm=this;
            if(this.selectedRoles.length==0){
                this.$message({
                    message: '请选择要删除的项目',
                    type: 'warning'
                });
            }else{
                this.$confirm('确定删除这'+this.selectedRoles.length+'项吗？', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    if (vm.deleteFlag) {
                        this.$http.delete(API.deleteRole+'/'+this.selectedRoles.join()).then((response) => {
                            if(response.body.status == 0) {
                                vm.getStore();
                                vm.$message({
                                    message: '删除成功',
                                    type: 'success'
                                });
                                vm.dialogAddVisible = false;
                                vm.dialogEditVisible = false;
                            }
                        });
                    } else {
                        this.$message({
                            type: 'warning',
                            message: '只能删除自己创建的'
                        });
                    }
                    
                }).catch(() => {
                    this.$message({
                        type: 'info',
                        message: '已取消删除'
                    });
                });
            }
        },
        handleSelectionChange:function(val){
            var vm = this;
            vm.selectedRoles=val.map(function (value) {
                if (value.creatorId !== localStorage.userId) {
                     vm.deleteFlag = false;
                } 
                return value.id;
            });
        },
        handleUsersSelectionChange:function(val){
            this.users.selectedItems=val.map(function (value) {
                return value.id;
            });
        },
        search:function(){
            this.getStore();
        },
        searchUser:function(query){
            this.$http.get(API.getRoles+'/'+this.currentId+'/users/out', {params:{searchKey: query, deptId: localStorage.deptId}}).then((response) => {

                this.users.searchUsers = response.body.data.map(item => {
                    return { value: item.id, label: item.realName+'('+item.accountName+')' };
                });
                //this.users.total = response.body.data.total;
                //this.users.loading = false;
            }, (response) => {
                // error callback
                //this.users.loading = false;
            });
        },
        reset:function(type){
            this.role={
                id: '',
                innerName: '',
                roleName:'',
                displayOrder:0,
                creatorId: '',
                deptId: '',
                createTime: ''
            };
            this.dialogAddVisible = false;
            this.dialogEditVisible = false;
        },
        submit:function(formName){

            var vm=this;

            //validate
            this.$refs[formName].validate((valid) => {
                if (valid) {
                    var data=vm.role;
                    if(formName=='editForm'){
                        data.id=vm.currentId;
                    }else{
                        data.id='';
                        data.creatorId = localStorage.userId;
                        data.deptId = localStorage.deptId;
                    }
                    data.createTime = '';

                    this.$http.post(API.postRole, data, {emulateJSON: false}).then((response) => {
                        //console.log(response.body);

                        if(response.body.status == 0) {
                            vm.getStore();
                            vm.$message({
                                message: '保存成功',
                                type: 'success'
                            });
                            vm.dialogAddVisible = false;
                            vm.dialogEditVisible = false;
                        }

                    });
                } else {
                    //console.log('error submit!!');
                    return false;
                }
            });
        },
        addUser:function(){
            console.log(this.users.addUser);
            var id=this.users.addUser;
            if(id==''){
                this.$message({
                    message: '请选择要添加的人员',
                    type: 'warning'
                });
            }
            this.$http.post(API.getRoles+'/'+this.currentId+'/users/', {userId:id},{emulateJSON: true}).then((response) => {

                this.getUsersStore();
                this.$message({
                    message: '添加成功',
                    type: 'sucess'
                });

            }, (response) => {
                // error callback
            });
        },
        handleRemoveUser:function(index,row){
            var vm=this;
            this.$confirm('确定移除'+row.realName+'吗？', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                this.$http.delete(API.deleteRole+'/'+this.currentId+'/users/'+row.id).then((response) => {
                    if(response.body.status == 0) {
                        vm.getUsersStore();
                        vm.$message({
                            message: '移除成功',
                            type: 'success'
                        });
                    }
                });
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消删除'
                });
            });
        },
        getStore:function(){

            this.loading = true;
            this.$http.get(API.getRoles, {
                    params:{
                        offset: this.limit*(this.currentPage - 1), 
                        limit: this.limit, 
                        searchKey: this.searchKey,
                        userId:localStorage.userId,
                        deptId: localStorage.deptId
                    }
            
                }).then((response) => {

                this.tableData = response.body.data.rows;
                this.total = response.body.data.total;
                this.loading = false;
            }, (response) => {
                // error callback
            });
        },
        getUsersStore:function(){

            //this.users.loading = true;
            this.$http.get(API.getRoles+'/'+this.currentId+'/users', {params:{offset: this.users.limit*(this.users.currentPage - 1), limit: this.users.limit, searchKey: this.users.searchKey}}).then((response) => {

                this.users.tableData = response.body.data.rows;
                this.users.total = response.body.data.total;
                //this.users.loading = false;
            }, (response) => {
                // error callback
                //this.users.loading = false;
            });
        },
        handleMemberManager:function(index,row){
            var vm=this;
            vm.users.dialogVisible=true;
            vm.currentId=row.id;
            vm.getUsersStore();

        },
        handleMenu(index,row) {
            this.menuManageVisible = true;
            this.currentId = row.id;
            this.$http.get(API.menu + "/users/" + localStorage.userId + "/roles/" + row.id).then((response) => {
                //  console.log("获取角色中菜单树： ", response.body.data);

                this.treeJson = response.body.data.treeJson;
                this.treeChecks = response.body.data.treeChecks;
            }); 
        },
        submitMenuMange() {
            console.log("选择的id有：", this.$refs.tree.getCheckedKeys());
            let nodesDOM = this.$refs.tree.$el.querySelectorAll('.el-tree-node');
            let nodesVue = [].map.call(nodesDOM, node => node.__vue__);
            let indeterminateNode = nodesVue.filter(item => item.indeterminate === true);
            let indeterminateNodeId = [];
            indeterminateNode.forEach(function(element) {
                console.log(element.node.data.id);
                indeterminateNodeId.push(element.node.data.id);
            }, this);
            // console.log(nodesVue.filter(item => item.indeterminate === true));

            var menuIds = this.$refs.tree.getCheckedKeys().join(",");
            var indeterminateNodeIds = indeterminateNodeId.join(",");

            this.$http.post(API.rootPath + "/roles/" + this.currentId + "/menus", {menuIds: menuIds, indeterminateIds: indeterminateNodeIds}, {emulateJSON: true}).then((response) => {
                // console.log(response.body.data);
                if(response.body.status == 0) {
                    this.$message({
                        message: '保存成功',
                        type: 'success'
                    });
                    this.menuManageVisible = false;
                }
            }); 
        },
        // checkChange(data, checked, indeterminate, node) {
        //     console.log(data, checked, indeterminate, node);

        //     if(this.canDG) {
        //         console.log('可以递归');
        //         this.canDG = false;
        //         if(checked) {
        //             this.checekdParent(node);
        //             this.checkedChildren(node);
        //         }
                
        //         console.log("递归结束");
        //         this.canDG = true;
        //     }
            
        //     // //如果是被选择的话，则给父节点也给选中
        //     // if(checked) {
        //     //     //父节点选中之后也会自动触发该方法，免去了我们自己写递归
        //     //     node.parent.checked = true;
        //     //     if(!this.setChildFlag) {
                    
        //     //          //如果含有子节点，则给子节点里都选上，应该给一个参数来判断，这是给子节点仅限的递归操作。
        //     //         if(node.childNodes != null) {
        //     //             this.setChildFlag = true;
        //     //             node.childNodes.forEach(function(element) {
        //     //                 console.log("死循环吗");
        //     //                 element.checked = true;
        //     //             }, this);
        //     //         }
        //     //     }

        //     // } else {
        //     //     //如果是取消选择，则要判断父节点下所有的孩子是否都没有选择，如果是，则给父节点也给取消掉
        //     //     var childrenChecked = false;
        //     //     var children = node.parent.childNodes;
        //     //     console.log("childdddddddd", children);

        //     //     if(children != null) {
        //     //         children.forEach(function(element) {
        //     //             if(element.checked) {
        //     //                 childrenChecked = true;
        //     //             }
        //     //         }, this);
        //     //     }


        //     //     if(!childrenChecked) {
        //     //         node.parent.checked = false;
        //     //     }
        //     // }
        // },
        // currentChangeMenu(data, node) {
        //     console.log(data, node);
        // },
        // checekdParent(node) {
        //     console.log("递归中set parent");
        //     if(node.parent != null) {
        //         node.parent.checked = true;
        //         this.checekdParent(node.parent);
        //     }
        // },
        // checkedChildren(node) {
        //     console.log("递归中set child");

        //     //如果含有子节点，则给子节点里都选上，应该给一个参数来判断，这是给子节点仅限的递归操作。
        //     if(node.childNodes != null) {
        //         node.childNodes.forEach(function(element) {
        //             element.checked = true;
        //             this.checkedChildren(element);
        //         }, this);
        //     }
        // }
    },
    created() {
        this.getStore();
    }
};
</script>

